package com.wfy.common.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import com.wfy.common.config.Global;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

/**
 * 上传文件
 */
public final class FileUpload {

    private static final Logger LOGGER = LoggerFactory.getLogger(FileUpload.class);

    private FileUpload() {

    }

    /**
     * @param file     //文件对象
     * @param filePath //上传路径
     * @param fileName //文件名
     * @return 文件名
     */
    public static String fileUp(MultipartFile file, String filePath, String fileName) {
        String extName = "";
        try {
            if (file.getOriginalFilename().lastIndexOf(Global.DEFAULT_POINT) >= 0) {
                extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(
                        Global.DEFAULT_POINT));
            }
            copyFile(file.getInputStream(), filePath,
                    fileName + extName).replaceAll(Global.DEFAULT_PARAM_SPLIT,
                    "");
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
        return fileName + extName;
    }

    /**
     * 写文件到当前目录的upload目录中
     *
     * @param in
     * @param dir
     * @param realName
     * @throws IOException
     */
    private static String copyFile(InputStream in, String dir, String realName)
            throws IOException {
        File file = new File(dir, realName);
        if (!file.exists()) {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            file.createNewFile();
        }
        FileUtils.copyInputStreamToFile(in, file);
        return realName;
    }
}
